/*
 * @Description:
 * @Version: 1.0
 * @Author: liguansheng
 * @Date: 2022-07-25 11:48:10
 * @LastEditors: liguansheng liguansheng
 * @LastEditTime: 2023-03-21 15:44:05
 */
import { asyncRoutes, constantRoutes } from '@/router/index'
import { RouteRecordRaw } from 'vue-router'
import { ref } from 'vue'
import { defineStore } from 'pinia'
import { applicationConfiguration } from '@/http/common'

function hasPermission (grantedPolicies: any, route: RouteRecordRaw) {
  if (route.meta && route.meta.policy) {
    const policy: string = (route.meta.policy as string)
    return grantedPolicies[policy]
  } else {
    return true
  }
}

export function filterAsyncRoutes (routes: RouteRecordRaw[], grantedPolicies: RouteRecordRaw[]):RouteRecordRaw[] {
  const res: RouteRecordRaw[] = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(grantedPolicies, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, grantedPolicies)
        if (tmp.children.length <= 0) return
      }

      if (route.meta && route.meta.policy === '') {
        if (tmp.children && tmp.children.length > 0) {
          res.push(tmp)
        }
      } else {
        res.push(tmp)
      }
    }
  })
  return res
}

// 使用setup模式定义
export const permissionStore = defineStore('permissionStore', () => {
  const abpConfig = ref<any>(null)
  const policies = ref<any>({})
  const addRoutes = ref<RouteRecordRaw[]>([])
  const routeList = ref<RouteRecordRaw[]>([])

  function SET_ROUTES (routes: RouteRecordRaw[]) {
    addRoutes.value = routes
    routeList.value = constantRoutes.concat(routes)
  }
  function SET_ABPCONFIG (config:any) {
    abpConfig.value = config
    policies.value = config.auth.grantedPolicies
  }
  function generateRoutes (grantedPolicies:RouteRecordRaw[]):Promise<RouteRecordRaw[]> {
    return new Promise(resolve => {
      const accessedRoutes = filterAsyncRoutes(asyncRoutes, grantedPolicies)
      SET_ROUTES(accessedRoutes)
      // console.log(accessedRoutes)
      resolve(accessedRoutes)
    })
  }
  function getApplicationConfiguration () {
    return new Promise((resolve, reject) => {
      applicationConfiguration()
        .then((response) => {
          SET_ABPCONFIG(response)
          resolve(response)
        })
        .catch((error:any) => {
          reject(error)
        })
    })
  }

  return { policies, abpConfig, routeList, generateRoutes, getApplicationConfiguration }
})
